﻿using UnityEngine;
using System.Collections;

#if false
public class ShakeCamera : MonoBehaviour
{

    private float shakeTime = 0.0f;
    private float fps = 20.0f;
    private float frameTime = 0.0f;
    private float shakeDelta = 0.005f;
    public Camera cam;
    public bool isshakeCamera = false;
    // Use this for initialization
    void Start()
    {
        shakeTime = 1.0f;
        fps = 20.0f;
        frameTime = 0.03f;
        shakeDelta = 0.005f;
    }

    // Update is called once per frame
    void Update()
    {
        if (isshakeCamera)
        {
            if (shakeTime > 0)
            {
                shakeTime -= Time.deltaTime;
                if (shakeTime <= 0)
                {
                    cam.rect = new Rect(0.0f, 0.0f, 1.0f, 1.0f);
                    isshakeCamera = false;
                    shakeTime = 1.0f;
                    fps = 20.0f;
                    frameTime = 0.03f;
                    shakeDelta = 0.005f;
                }
                else
                {
                    frameTime += Time.deltaTime;

                    if (frameTime > 1.0 / fps)
                    {
                        frameTime = 0;
                        cam.rect = new Rect(shakeDelta * (-1.0f + 2.0f * Random.value), shakeDelta * (-1.0f + 2.0f * Random.value), 1.0f, 1.0f);

                    }
                }
            }
        }

    }

    public void shakeCamera()
    {
        isshakeCamera = true;
    }
}

#else

public class ShakeCamera : MonoBehaviour
{
    // Transform of the camera to shake. Grabs the gameObject's transform
    // if null.
    public Transform camTransform;

    // How long the object should shake for.
    public float duration = 0f;

    // Amplitude of the shake. A larger value shakes the camera harder.
    public Vector3 shakeDistance = new Vector3(1, 1, 1);
    private float decreaseFactor = 1.0f;

    Vector3 originalPos;

    void Awake()
    {
        if (camTransform == null)
        {
            camTransform = GetComponent(typeof(Transform)) as Transform;
        }
    }

    void OnEnable()
    {
        originalPos = camTransform.localPosition;
    }

    void Update()
    {
        Update(Time.deltaTime);
    }

    public void Update(float deltaTime)
    {
        if (duration > 0)
        {
            camTransform.localPosition = originalPos
                + new Vector3(
                    Random.RandomRange(-1F, 1) * shakeDistance.x,
                    Random.RandomRange(-1F, 1) * shakeDistance.y,
                    Random.RandomRange(-1F, 1) * shakeDistance.z
                );

            duration -= deltaTime * decreaseFactor;
        }
        else
        {
            duration = 0f;
            camTransform.localPosition = originalPos;
            enabled = false;
        }
    }

    public void Reset()
    {
        if (camTransform == null) return;

        originalPos = camTransform.localPosition;
        enabled = true;
    }


}
#endif